// pages/common/chat-window/chat-window.js
var utils = require('../../../utils/util.js');
var api = require('../../../config/api.js');

const app = getApp();
var inputVal = '';
var msgList = [];
var screenHeight = 0;
var windowHeight = 0;
var keyHeight = 0;
var refreshTimer;
var userPullup = false;

/**
 * 初始化数据
 */
function initData(that) {
  inputVal = '';

  msgList = []
  that.setData({
    msgList,
    inputVal
  })
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    inputBottom: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let local = 0;
    let peer = 0;
    if(options.local){
      console.log("chat-window: local = " + options.local);
      local = options.local;
    }

    if(options.peer){
      console.log("chat-window: peer = " + options.peer);
      peer = options.peer;
    }
    let sender = '';
    //if(app.globalData.isNurse){
    if(app.globalData.role == "nurse"){
      sender = 'n';
    }else{
      sender = 'p';
    }
    this.getScrollHeight();
    initData(this);
    console.log("msgList.length = " + msgList.length);
    this.setData({
      cusHeadIcon: app.globalData.avatarUrl,
      local: local,
      peer: peer,
      role: sender
    });
    this.refreshChatRecords();
    this.startTimerToGetRecords();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearInterval(refreshTimer);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

   /**
   * 获取聚焦
   */
  focus: function(e) {
    keyHeight = e.detail.height;
    this.setData({
      scrollHeight: this.data.scrollHeight - keyHeight
    });
    this.setData({
      toView: 'msg-' + (msgList.length - 1),
      inputBottom: keyHeight
    });
  },

  //失去聚焦(软键盘消失)
  blur: function(e) {
    this.setData({
      scrollHeight: this.data.scrollHeight + keyHeight,
      inputBottom: 0
    })
    this.setData({
      toView: 'msg-' + (msgList.length - 1)
    })

  },

  /**
   * 发送点击监听
   */
  sendClick: function(e) {
    let that = this;
    if(e.detail.value && e.detail.value.length != 0){
      msgList.push({
        speaker: 'customer',
        contentType: 'text',
        headIcon: app.globalData.avatarUrl,
        content: e.detail.value
      })
      inputVal = '';
      this.setData({
        msgList,
        inputVal,
        toView: 'msg-' + (msgList.length - 1)
      });
  
      that.sendMessage('text', e.detail.value);
    }else{
      wx.showToast({
        title: '发送内容不能为空...',
        icon: 'none',
        duration: 2000
      });
      return;
    }
  },

  /**
   * 退回上一页
   */
  toBackClick: function() {
    wx.navigateBack({})
  },

  getScrollHeight: function(){
    let that = this;
    wx.getSystemInfo({
      success: function(res) {
        windowHeight = res.windowHeight;
        screenHeight = res.screenHeight;
        console.log("windowHeight = " + windowHeight);
        console.log("screenHeight = " + screenHeight);
        let inputRoomWrap = wx.createSelectorQuery();
        inputRoomWrap.select('.inputRoom').boundingClientRect();
        let inputHeight = 0;
        inputRoomWrap.exec(function (res) {
          console.log("inputRoom height = " + res[0].height);
          inputHeight = res[0].height;
          var temp = windowHeight - inputHeight;
          console.log("scroll height = " + temp );
          that.setData({
            scrollHeight: temp,
          });
          // 必须在scrollHeight 设置之后再更新toView 才有效
          console.log("set to view " + (msgList.length - 1));
          that.setData({
            toView: 'msg-' + (msgList.length - 1)
          });
        });
      }
    });
  },

  // 点击图片预览
  imgPreview: function(event){
    var src = event.currentTarget.dataset.src;
    console.log("imgPreview + " + src);
    wx.previewImage({
      current: src,
      urls: [src]
    });
  },

  // 从图库选择图片
  chooseImage: function(){
    let that = this;
    wx.chooseImage({
      success: function(res){
        console.log("choose image: " + res.tempFilePaths);
        for(var i=0; i<res.tempFilePaths.length; i++){
          // 确定服务器端接口后再传
          wx.uploadFile({
            url: api.storageUpload,
            filePath: res.tempFilePaths[i],
            name: 'file',
            formData: {
            },
            success: function(success_res){
              console.log("image upload sucess:" + JSON.stringify(success_res));
              let url = res.tempFilePaths[i];
              
              if(success_res.statusCode == 200){
                let data = JSON.parse(success_res.data);
                console.log("data: " + JSON.stringify(data));
                url = data.data.url;
              }
              console.log("url: " + url);
              that.sendMessage('image', url);
            }
          });
          msgList.push({
            speaker: 'customer',
            headIcon: app.globalData.avatarUrl,
            contentType: 'image',
            content: res.tempFilePaths[i]
          });
          inputVal = '';
          that.setData({
            msgList,
            inputVal,
            toView: 'msg-' + (msgList.length - 1)
          });
        }
      }
    });
  },

  //发送消息接口
  sendMessage: function(type, content){
    let that = this;
    let patientId = 0;
    let nurseId = 0;
    let sender = '';
    if(app.globalData.role == "nurse"){
      patientId = that.data.peer;
      nurseId = that.data.local;
      sender = 'n';
    }else{
      patientId = that.data.local;
      nurseId = that.data.peer;
      sender = 'p';
    }
    utils.request(api.messageSend, {
      patientId: parseInt(patientId),
      nurseId: parseInt(nurseId),
      type: type,
      sender: sender,
      content: content
    }, 'POST').then(function(res){
      console.log("messageSend: " + JSON.stringify(res));
    });
  },

  //获取聊天记录
  refreshChatRecords: function(){
    let that = this;
    let patientId = 0;
    let nurseId = 0;
     if(app.globalData.role == "nurse"){
      patientId = that.data.peer;
      nurseId = that.data.local;
    }else{
      patientId = that.data.local;
      nurseId = that.data.peer;
    }
    utils.request(api.getMessageRecords, {
      patientId: parseInt(patientId),
      nurseId: parseInt(nurseId),
      sender: that.data.role
    }).then(function(res){
      // console.log("getChatRecords: " + JSON.stringify(res));
      var loadAll = msgList.length == 0;
      for(var i in res.data.list){
        var speaker = res.data.list[i].sender == that.data.role? 'customer': 'server';
        var headIcon = '/static/common/image/default.png';
        if(res.data.list[i].avatarUrl){
          headIcon = res.data.list[i].avatarUrl
        }else{
          if(res.data.list[i].sender == that.data.role){
            headIcon = app.globalData.avatarUrl;
          }
        }
        if(loadAll){
          msgList.push({
            id: res.data.list[i].id,
            speaker: speaker,
            contentType: res.data.list[i].type,
            content: res.data.list[i].content,
            headIcon: headIcon
          });
        }else{
          if(!res.data.list[i].status 
            && res.data.list[i].sender != that.data.role){
            wx.vibrateShort();
            msgList.push({
              id: res.data.list[i].id,
              speaker: speaker,
              contentType: res.data.list[i].type,
              content: res.data.list[i].content,
              headIcon: headIcon
            });
          }
        }
      }
      if(userPullup){
        that.setData({
          msgList
        });
      }else{
        that.setData({
          msgList,
          toView: 'msg-' + (msgList.length - 1)
        });
      }
    });
  },

  //定时去服务武器拉取未读信息
  startTimerToGetRecords: function(){
    let that = this;
    refreshTimer = setInterval(that.refreshChatRecords, 2000);
  },

  scroll: function(e) {
    //console.log(e);
    var scrollHeight =  e.detail.scrollHeight;
    var scrollTop = e.detail.scrollTop;
    var atBottom = (scrollHeight - scrollTop) <= (this.data.scrollHeight + 10);
    if(!atBottom){
      console.log("not at bottom");
      userPullup = true;
    }else{
      console.log("at bottom");
      userPullup = false;
    }
  },
})